from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet
import json

from .models import *
from user.models import *
from .serializers import *
from user.serializers import *
from .models import *
from user.models import UserModel, GoodTypeModel, GoodsModel
from user.utils import redis_conn


from rest_framework import viewsets
from rest_framework.response import Response
from django.contrib.auth.hashers import make_password


# 商家视图
class ShopsView(viewsets.ViewSet):
    # 入驻申请
    def shops_register(self,request):
        try:
            nickname = request.data.get("nickname")
            password = request.data.get("password")
            mobile = request.data.get("mobile")
            address = request.data.get("address")

            if not all([nickname, password, mobile, address]):
                return Response({"code": 2, "msg": "提交信息不完整！"})

            user = ShopsModel.objects.filter(nickname=nickname,is_delete=False).first()
            if user:
                return Response({"code": 3, "msg": "名称已存在！"})

            user = UserModel.objects.filter(mobile=mobile,is_delete=False).first()
            if user:
                return Response({"code": 1, "msg": "手机号已注册！"})

            user = ShopsModel.objects.filter(mobile=mobile, is_delete=False).first()
            if user:
                return Response({"code": 1, "msg": "手机号已注册！"})

            hash_pwd = make_password(password)
            ShopsModel.objects.create(nickname=nickname, password=hash_pwd, mobile=mobile, address=address)
            return Response({"code": 0, "msg": "注册成功！"})

        except Exception as e:
            print("错误", e)

    # 获取商家用户信息
    def shops_dict(self, request):
        try:
            user_id = request.query_params.get('user_id')
            # user_id = request.data.get('user_id')
            user_type = request.data.get("user_type")

            user = ShopsModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"code": 400, "msg": "用户不存在！"})
            # if user_type != 2:
            #     return Response({"code": 400, "msg": "非法请求！"})

            ser = ShopsSer(user)
            return Response({"code": 200, "msg": "ok！","data": ser.data})
        except Exception as e:
            print("错误", e)

    # 修改用户信息
    def up_user(self, request):
        try:
            user_id = request.data.get('user_id')
            # user_id = request.data.get("user_id")
            print(user_id)
            nickname = request.data.get("nickname")
            avatar_url = request.data.get("avatar_url")
            intro = request.data.get("intro")
            address = request.data.get("address")
            password = request.data.get("password")
            work_time = request.data.get("work_time")
            start_price = request.data.get("start_price")

            flag = ShopsModel.objects.filter(nickname=nickname, is_apply=True, is_delete=False).exclude(id=user_id).count()
            if flag != 0:
                return Response({"code": 1, "msg": "该用户名已存在！"})

            user = ShopsModel.objects.filter(id=user_id, is_apply=True, is_delete=False)
            if not user:
                return Response({'code': 2, 'msg': '用户不存在'})
            if nickname:
                user.update(nickname=nickname)
            if avatar_url:
                user.update(avatar_url=avatar_url)
            if intro:
                user.update(intro=intro)
            if address:
                user.update(address=address)
            if password:
                pwd = make_password(password)
                user.update(password=pwd)
            if work_time:
                user.update(work_time=work_time)
            if start_price:
                user.update(start_price=start_price)
            return Response({
                'code': 200,
                'msg': '修改成功',
            })
        except Exception as e:
            print("错误", e)

    # 查询商家下的分类 和商品
    def shops_list(self, request, pk):
        try:
            # 先查询店家
            shops = ShopsModel.objects.filter(id=pk, is_delete=False)
            # 根据店家反查询分类信息
            goods_type = shops.first().goodtypemodel_set.filter(is_delete=False).all()

            good_list = GoodTypeSer(goods_type, many=True)
            goods_type = json.loads(json.dumps(good_list.data))
            for i in goods_type:
                # 根据分类信息反查询商品详情
                shops_good = GoodsModel.objects.filter(type_id=i['id'], is_delete=False).all()
                goods_ser = GoodSer(shops_good, many=True)
                goods = json.loads(json.dumps(goods_ser.data))
                i['goods_list'] = goods

            return Response({"code": 200, "msg": "查询成功", "data": goods_type})
        except Exception as e:
            print("查询失败", e)
            return Response({"code": 400, "msg": "查询失败"})


# 获取所有商家信息
class ShopsViewSer(ViewSet):
    def shops_list(self, request):
        try:
            shops = ShopsModel.objects.all()
            ser = ShopsSer(shops, many=True)
            return Response({"code": 200, "msg": "获取所有商家成功", "data": ser.data})

        except Exception as e:
            print(e)
            return Response({"code": 400, "msg": "获取失败"})


# 菜品类别
class GoodsTypeView(ViewSet):
    # 获取
    def list(self, request):
        try:
            # user_id = request.data.get("user_id")
            user_id = request.query_params.get('user_id')
            print(user_id)
            goods_type = GoodTypeModel.objects.filter(shops_id=user_id, is_delete=False)
            ser = GoodTypeSer(goods_type, many=True)
            return Response({"code": 200, "msg": "获取成功", "goods": ser.data})
        except Exception as e:
            print("错误", e)
            return Response({"code": 400, "msg": "获取失败"})

    # 添加类别
    def add(self, request):

            shops_id = request.data.get('shops_id')
            int(shops_id)
            name = request.data.get("name")
            # shops = request.data.get("shops")
            try:

                GoodTypeModel.objects.create(name=name, shops_id=shops_id)

                return Response({"code": 200, "msg": "添加成功"})
            except Exception as e:
                print("错误", e)
                return Response({"code": 400, "msg": "添加失败"})

    # 修改类别
    def update(self, request):
        try:
            # user_id = request.query_params.get("user_id")
            user_id = request.data.get("user_id")
            id = request.data.get("id")
            name = request.data.get("name")
            # print(type(id))
            # print(type(user_id))
            print(user_id, id, name)

            goods_type = GoodTypeModel.objects.filter(id=id, shops_id=user_id, is_delete=False).first()
            # print('====',goods_type)
            # if not goods_type:
            #     return Response({"code": 1, "msg": "类别不存在！"})

            goods_type_data = {
                "id": id,
                "name": name,
                "shops": user_id,
            }
            serializer = GoodTypeSer(instance=goods_type, data=goods_type_data)
            serializer.is_valid(raise_exception=True)
            serializer.save()

            return Response({"code": 200, "msg": "修改成功"})
        except Exception as e:
            print("修改失败的原因", e)

    # 获取单个类别
    def good_get(self, request, pk):
        try:
            user_id = request.query_params.get("user_id")
            # user_id = request.data.get("user_id")
            goods_type = GoodTypeModel.objects.filter(shops_id=int(user_id), id=pk, is_delete=False)
            ser = GoodTypeSer(goods_type, many=True)
            return Response({"code": 200, "msg": "获取成功", "goods": ser.data})
        except Exception as e:
            print("错误", e)
            return Response({"code": 400, "msg": "获取失败"})

    # 删除类别
    def delete(self, request, pk):
        try:
            user_id = request.query_params.get("user_id")
            # user_id = request.data.get("user_id")
            int(user_id)
            print(type(user_id))
            goods_type = GoodTypeModel.objects.filter(id=pk, shops_id=user_id, is_delete=False)
            if not goods_type:
                return Response({"code": 400, "msg": "类别不存在！"})

            goods_type.update(is_delete=True)

            return Response({"code": 200, "msg": "删除成功"})
        except Exception as e:
            print("错误", e)
            return Response({"code": 400, "msg": "删除失败"})


# 菜品
class GoodsView(ViewSet):
    # 获取
    def list(self, request):
        try:

            # user_id = request.data.get("user_id")
            user_id = request.query_params.get("user_id")
            id = request.query_params.get("id")

            goods_type = GoodTypeModel.objects.filter(shops_id=user_id, is_delete=False)
            print(goods_type)
            temp = []
            for i in goods_type:
                goods = i.goodsmodel_set.filter(is_delete=False)
                temp += goods

            ser = GoodSer(temp, many=True)
            return Response({"code": 200, "msg": "成功", "data": ser.data})
        except Exception as e:
            print("错误", e)
            return Response({"code": 400, "msg": "失败"})

    # 添加菜品
    def add(self, request):
        try:
            user_id = request.query_params.get("user_id")

            name = request.data.get("name")
            price = request.data.get("price")
            image = request.data.get("image")
            type = request.data.get("type")

            goods_data = {
                "name": name,
                "price": price,
                "image": image,
                "type": type,
            }
            serializer = GoodSer(data=goods_data)
            serializer.is_valid(raise_exception=True)
            serializer.save()

            return Response({"code": 200, "msg": "添加成功"})
        except Exception as e:
            print("错误", e)
            return Response({"code": 400, "msg": "添加失败"})

    # 修改菜品
    def update(self, request):
        try:
            user_id = request.query_params.get("user_id")

            id = request.data.get("id")
            name = request.data.get("name")
            price = request.data.get("price")
            image = request.data.get("image")
            type = request.data.get("type")

            print(id, name, price, image, type)

            goods = GoodsModel.objects.filter(id=id, is_delete=False).first()
            # if not goods:
            #     return Response({"code": 1, "msg": "商品不存在！"})

            goods_data = {
                "id": id,
                "name": name,
                "price": price,
                "image": image,
                "type": type,
            }
            serializer = GoodSer(instance=goods, data=goods_data)
            serializer.is_valid(raise_exception=True)
            serializer.save()

            return Response({"code": 0, "msg": "修改成功！"})
        except Exception as e:
            print("失败的原因", e)

    # 删除菜品
    def delete(self, request, pk):
        try:
            user_id = request.query_params.get("user_id")
            # user_id = request.data.get("user_id")
            goods = GoodsModel.objects.filter(id=pk, is_delete=False).delete()
            return Response({"code": 200, "msg": "删除成功"})
        except Exception as e:
            print("错误", e)
            return Response({"code": 400, "msg": "删除失败"})

    # 根据分类查找菜品
    def good_get(self, request, pk):
        g1 = GoodTypeModel.objects.get(id=pk)

        good = g1.goodsmodel_set.all()

        goods_ser = GoodSer(good, many=True)

        return Response({"code": 200, "data": goods_ser.data})

    # 获取单条菜品的信息
    def good(self, request, pk):
        try:
            user_id = request.query_params.get("user_id")
            # user_id = request.data.get("user_id")
            print(user_id)
            goods = GoodsModel.objects.filter(id=pk, is_delete=False)
            ser = GoodSer(goods, many=True)
            return Response({"code": 200, "msg": "获取成功", "data": ser.data})
        except Exception as e:
            print("错误", e)
            return Response({"code": 400, "msg": "获取失败"})



